package com.scrawler.util;



import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**  
 * @Description: 描述
 * @author kuntang    
 * @version 1.0  
 * @created 2012-10-26 下午2:18:33 
 * Copyright (c) 2012 sohu,Inc. All Rights Reserved.
 */
@Service
public class UrlUtils {
	
	@Autowired
	private DataLib dataLib;
	private static final Log LOG = LogFactory.getLog(UrlUtils.class);
	public int getNidByUrl(String url){
		int id = -1;
		Pattern p = Pattern.compile("/n\\d+");
		Matcher matcher = p.matcher(url);
		int start  = 0;
		if(matcher.find()){
			start = matcher.start();
		}
		int end = url.indexOf(ConstantUtils.URL_TAIL_STRING);
		/** +2是因为要去掉前面的/n  */
		String idStr = url.substring(start+2,end);
		if(idStr != null && idStr.matches("\\d+")){
			id = Integer.parseInt(idStr);
		}
		return id;
	}
	
	public int classfyUrl(int channelId,Map<String,Float>  linkScores){
		int i=0;
		for(String key : linkScores.keySet()){
			int nid = getNidByUrl(key);
			if(nid >0 && !dataLib.pageViewContainsKey(channelId, nid)){
				// newsMap.put(id, linkScores.get(key));
				dataLib.addPageViewItem(channelId, nid,  linkScores.get(key));
				i++;
			}
		}
		return i;
	}
	
	public int megerUrl(Map<String,Float> source,Map<String,Float> desc){
		if(desc == Collections.EMPTY_MAP){
			LOG.info("empty Map<String,Float> desc...........");
			return 0;
		}
		int i=0;
		for(Map.Entry<String, Float> entry : source.entrySet()){
			String key = entry.getKey();
			if(!desc.containsKey(key)){
				try{
					desc.put(key, entry.getValue());
				}catch(Exception e){
					LOG.error("megerUrl map.put() exception.....",e);
				}
				i++;
			}
		}
		return i;
	}
	
	/**
	 * @Description:
	 * @Date: 2012-10-26
	 * @param: @param args
	 * @return: void
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String url = "http://sports.sohu.com/20121026/n355767034.shtml";
		Pattern p = Pattern.compile("/n\\d+");
		Matcher matcher = p.matcher(url);
		int i  = 0;
		if(matcher.find()){
			i = matcher.start();
			System.out.println(i);
		}
		int end = url.indexOf(ConstantUtils.URL_TAIL_STRING);
		String s = url.substring(i+2,end);
		System.out.println(s);
	}

}
